package com.miniserver.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.PropertyConfigurator;

import com.miniserver.tql.TqlGlobal;
import com.miniserver.util.AppConfiguration;
import com.miniserver.util.DKeyDesEncrypt;
import com.miniserver.util.LogUtil;
/*import org.quartz.CronScheduleBuilder;*/

/**
 * Listener类，用于启动时初始化系统物理路径，停止时关闭数据库连接和Memcache连接
 * 
 * @author zzlt104
 * 
 */
public class AppListener implements ServletContextListener {
	private static LogUtil log = LogUtil.getLogUtil("AppListener");
	/**
	 * 停止数据库连接
	 */
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// AppConfiguration.shutdown();
		try {
			TqlGlobal.getTqlMaster().destroy();
			TqlGlobal.destory();
		} catch (Exception e) {
			log.error("contextDestroyed", e);
		}
	}

	/**
	 * 初始化系统物理路径 log配置文件和商品数据
	 */
	@Override
	public void contextInitialized(ServletContextEvent content) {
		if (StringUtils.isBlank(AppConfiguration.getWebRootName())) {
			ServletContext context = content.getServletContext();
			String paramName = context.getInitParameter("webAppRootKey");
			System.setProperty(paramName, context.getRealPath(""));			
			String logConfigPath = context.getRealPath("/WEB-INF/props/log4j.properties");
			PropertyConfigurator.configure(logConfigPath);
			String dataDir = context.getRealPath("/WEB-INF/props");
			DKeyDesEncrypt.encryptConfigFile(dataDir, new String[] { "xml","cfg","sql"});
			dataDir = context.getRealPath("/WEB-INF/data");
			DKeyDesEncrypt.encryptConfigFile(dataDir,new String[]{"xml","cfg","sql"});
			AppConfiguration.setWebRootName(context.getInitParameter("webAppRootKey"));
			TqlGlobal.init(context.getRealPath(""));
		}	
		
	}
}
